package com.idb.utils;

import cn.hutool.core.io.file.FileWriter;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.CronTask;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.idb.yml.OpsYml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class YmlUtils {
    private YmlUtils() {

    }

    private static class Singleton {
        private static final ObjectMapper MAPPER = createObjectMapper();
        private Singleton() {

        }
        private static ObjectMapper createObjectMapper() {
            final YAMLFactory yamlFactory = new YAMLFactory()
                    .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false)
                    .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
                    .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true)
                    .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false)
                    .configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false);

            return new ObjectMapper(yamlFactory)
                    .setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
                    .enable(SerializationFeature.INDENT_OUTPUT)
                    .disable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)
                    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                    .disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
        }
    }

    public static <T> T load(String ymlPath,Class<T> clazz) throws IOException {
        ObjectMapper mapper = Singleton.MAPPER;
        return mapper.readValue(new File(ymlPath),clazz);
    }

    public static void dump(String ymlPath,Object from) throws IOException {
        ObjectMapper mapper = Singleton.MAPPER;
        File file = new File(ymlPath);
        FileWriter fileWriter = FileWriter.create(file);
        fileWriter.writeFromStream(new ByteArrayInputStream(mapper.writeValueAsString(from).getBytes(StandardCharsets.UTF_8)));
    }

    public static void main(String[] args) {
        try {
            OpsYml opsYml = load("config/policy/ops.yml",OpsYml.class);
            dump("config/policy/ops2.yml",opsYml);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
